﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernateSample.Domain.Entities;
using NHibernate;

namespace NHibernateSample.Data
{
    public class QueryHql
    {
        protected ISession Session { get; set; }
        public QueryHql(ISession session)
        {
            Session = session;
        }

        public QueryHql()
        {
            Session = new NHibernateHelper().GetSession();
        }

        public IList<Customer> From()
        {
            //返回所有Customer类的实例
            return Session.CreateQuery("from Customer")
                .List<Customer>();
        }

        public IList<Customer> FromAlias()
        {
            //返回所有Customer类的实例，Customer赋予了别名customer
            return Session.CreateQuery("from Customer as customerA")
                .List<Customer>();
        }

        public IList<Customer> GetCustomersByFirstName(string firstName)
        {
            //写法1
            //return _session.CreateQuery("from Customer c where c.Firstname='" + firstname + "'")
            //    .List<Customer>();

            //写法2:位置型参数
            //return _session.CreateQuery("from Customer c where c.Firstname=?")
            //    .SetString(0, firstname)
            //    .List<Customer>();

            //写法3:命名型参数(推荐)
            return Session.CreateQuery("from Customer c where c.FirstName=:fn")
                .SetString("fn", firstName)
                .List<Customer>();
        }


        public IList<Customer> GetCustomersWithCustomerIdLessThan(int customerId)
        {
            return Session.CreateQuery("from Customer c where c.Id < :cid")
                .SetInt32("cid", customerId)
                .List<Customer>();
        }


    }
}
